package com.inspectortime.webapp.inspector;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.inspectortime.domain.type.InspectionStatus;
import com.inspectortime.util.SpringValidatorUtils;
import com.inspectortime.webapp.InspectionCriteria;
import com.inspectortime.webapp.InspectionCustomerInformationValidator;
import com.inspectortime.webapp.InspectionExtraInformationValidator;
import com.inspectortime.webapp.InspectionPropertyInformationValidator;
import com.mkode.util.java.lang.ClassUtils;

/**
 * @author mkvalsvik
 * 
 */
public class EditInspectionFormValidator implements Validator {
	
	private InspectionPropertyInformationValidator propertyValidator;
	private InspectionExtraInformationValidator extraValidator;
	private InspectionCustomerInformationValidator customerInfoValidator;	
	
	public EditInspectionFormValidator(InspectionPropertyInformationValidator propertyValidator, 
									   InspectionExtraInformationValidator extraValidator, InspectionCustomerInformationValidator customerInfoValidator) {
		this.propertyValidator = propertyValidator;
		this.extraValidator = extraValidator;
		this.customerInfoValidator = customerInfoValidator; 
	}	
	
	public boolean supports(Class clazz) {
		return ClassUtils.isInstanceOf(clazz, InspectionCriteria.class);
	}

	public void validate(Object obj, Errors errors) {
		InspectionCriteria criteria = (InspectionCriteria) obj;
		
		//Don't bother validating fields if the inspection is set to cancelled
		if (criteria.getInspection().getInspectionStatus() == InspectionStatus.CANCELLED) {
			return;
		}
		
		//Validate info common with Wizard
		propertyValidator.validate(criteria, errors);
		extraValidator.validate(criteria, errors);
		customerInfoValidator.validate(criteria, errors);
		
		if (!SpringValidatorUtils.isEmptyOrWhitespace(errors, "inspection.listingAgentPhoneNumber")) {
			SpringValidatorUtils.rejectInvalidPhone(errors, "inspection.listingAgentPhoneNumber");	
		}
		
	}
	
}
